/*
 *  Texture.cpp
 *  GLRender
 *
 *  Created by Teseo on 18.05.10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include "Texture.h"

Texture::Texture(const char* imgPath) : texTarget(GL_TEXTURE_2D), bounded(false) {
	bind(imgPath);	
}

Texture::Texture() : texTarget(GL_TEXTURE_2D), bounded(false) { }


void
Texture::bind(const char* imgPath)
{	
	if (bounded) {
		clear();
	}
	
	
        QImage img(imgPath);

	img = QGLWidget::convertToGLFormat(img);
	
	glGenTextures(1,&name);            // Allocate space for texture
	glBindTexture(texTarget, name); // Set our Tex handle as current
	glTexImage2D(texTarget, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
	
	// Specify filtering and edge actions
	//
	//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	
	glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	
	
	//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
	//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
	
	glTexParameteri(texTarget, GL_TEXTURE_WRAP_S,GL_CLAMP);
	glTexParameteri(texTarget, GL_TEXTURE_WRAP_T,GL_CLAMP);
	bounded = true;
}


void 
Texture::bind()
{
	glBindTexture(texTarget, name);
	
}

void 
Texture::enable()
{
	glEnable(texTarget);
}


void 
Texture::disable()
{
	glDisable(texTarget);
}

void 
Texture::clear()
{
	glDeleteTextures(1, &name);
	bounded = false;
}
